// src/pages/home/widgets/guestChannel/index.tsx
import styles from "@pages/home/widgets/channel/styles/styles.module.less";
import classNames from "classnames";
import useGuestChannels from "@pages/home/widgets/hooks/useGuestChannels";
import useChannelScroll from "@pages/home/widgets/common/scroll";
import { useNavigate, useParams } from "react-router-dom";
import {  useEffect, useRef } from "react";
export default function GuestChannel() {
  // 获取路由参数
  const { cid } = useParams();
  // 获取用于实现页面跳转的方法
  const navigate = useNavigate();
  // 获取访客频道列表
  const guestChannels = useGuestChannels();
  // 获取频道列表滚动逻辑
  const { scrollContainerRef, scrollHandler } = useChannelScroll();
  // 获取访客频道列表对应的 DOM 对象
  const guestChannelDOM = useRef<Record<number, HTMLDivElement>>({});
	
  // 检测高亮频道id变化
  useEffect(() => {
    // 获取高亮频道对应的 DOM 对象
    if (typeof cid !== "undefined") {
      const currentDOM = guestChannelDOM.current[Number(cid)];
      // 如果 DOM 对象不存在, 阻止程序继续运行
      if (typeof currentDOM === "undefined") return;
      // 设置高亮频道滚动位置
      scrollHandler(currentDOM);
    }
  }, [cid, guestChannelDOM, scrollHandler]);
  // 渲染视图
  return (
    <div className={styles.list} ref={scrollContainerRef}>
      {guestChannels.map((channel) => (
        <div
          key={channel.id}
          className={classNames(classNames(styles.item, {
            [styles.active]: channel.id === Number(cid),
          }))}
          ref={(element) => {guestChannelDOM.current[channel.id] = element!}}
          onClick={(event) => {scrollHandler(event.currentTarget);navigate(`/${channel.id}`)}}
        >
          {channel.name}
        </div>
      ))}
    </div>
  );
}